﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using System.Reflection;

namespace ToolMonitoring.WebApi.Dependency
{
	public static class IocExtensions
	{

		public static IServiceCollection AddDependency(
			this IServiceCollection services) 
		{

			/*
			var builder = new ContainerBuilder();

			builder.Populate(services);
			var container = builder.Build();

			services.AddAutofac(container);
			*/

			/*
			var assembly = Assembly.GetExecutingAssembly();
			var tranClasses = assembly
				.GetTypes()
				.Where(t => t.GetInterfaces().Contains(typeof(ITransientDependency)))
				.Where(t => !t.IsAbstract);

			foreach (var item in tranClasses)
			{
				services.AddTransient(item);

				var interfaces = item.GetInterfaces().Where(t => t != typeof(ITransientDependency));
				foreach (var inter in interfaces)
				{
					services.AddTransient(inter, item);
				}
				
				
			}

			// 注册ISingletonDependency
			var singleClasses = assembly.GetTypes()
				.Where(t => t.GetInterfaces().Contains(typeof(ISingletonDependency)))
				.Where(t => !t.IsAbstract);
			foreach (var item in singleClasses)
			{
				services.AddSingleton(item);
				// 过滤掉接口类型
				var interfaces = item.GetInterfaces()
						.Where(t => t != typeof(ISingletonDependency));
				
				foreach (var inter in interfaces)
				{
					services.AddSingleton(
						inter,
						x=>x.GetRequiredService(item));
				}
				
			}
			*/
			return services;
		}
	}
}
